package com.example.springbootmqdemo.aajuc;

/**
 *  JUC并发编程练习3
 *
 * @Author: Jam
 * @Create 2022/12/2 - 18:34
 * @Version 1.0  传统的生产者 消费者模式
 */
public class Thread3 {
    public static void main(String[] args) {
        TicketC ticket3  = new TicketC();

        //lambda表达式 (参数)->{代码}
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                try {
                    ticket3.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                try {
                    ticket3.decry();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }
}

class TicketC{ //资源类
    //属性 方法
    private  int number = 0;

    //+1
    public  synchronized void incr() throws InterruptedException {
//        if(number != 0){   --> if 换成while 防止虚假唤醒
        while (number != 0){
            //等待
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+"---"+number);
        number++;
        //通知其他线程 我+1完毕
        this.notifyAll();
    }

    //-1
    public  synchronized void decry() throws InterruptedException{
//        if(number != 0){   --> if 换成while 防止虚假唤醒
        while (number != 0){
            //等待
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+"---"+number);
        number--;
        //通知其他线程 我-1完毕
        this.notifyAll();
    }
}